package com.xe.gae.control;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreInputStream;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.FinalizationException;
import com.google.appengine.api.files.LockException;
import com.xe.gae.model.XEConfig;
import com.xe.gae.model.XEResource;

import com.xe.gae.model.XETree;
import com.xe.util.XUtil;

public class XEConfigManager {
	XEDataStorageService dss = new XEDataStorageService();
	XEResourcesManager rm = new XEResourcesManager();

	
	public String get(String key){
		XEConfig config = (XEConfig) dss.findByKey(XEConfig.class, key);
		if (config!=null){
		return config.getValue();
		}
		return null;
	}
	
	public String install() {

		XEConfig version = (XEConfig) dss.findByKey(XEConfig.class, "version");

		if (version == null) {
			version = installVersion100();
		}

		return version.getValue();
	}

	private XEConfig installVersion100() {

		XETree xtree = (XETree) dss.findByKey(XETree.class, "_XE");
		if (xtree == null) {
			xtree = new XETree();
			xtree.setName("_XE");
			dss.put(xtree);
			rm.getRoot(xtree);
		}

		XEConfig version = new XEConfig();
		version.setName("version");
		version.setValue("100");
		version = (XEConfig) dss.put(version);

		return version;
	}

	
	public  void install(BlobKey blobKey,XEResource root
			) {

		XEDataStorageService dss=new XEDataStorageService();
		XUtil util = new XUtil();
		XEResourcesManager rm=new XEResourcesManager();
    
		BlobstoreInputStream is;
		try {
			is = new BlobstoreInputStream(blobKey);
    
		final int BUFFER = 2048;
    
	    ZipInputStream zis= new ZipInputStream(is);
	    ZipEntry entry;
	    BlobInfoFactory infof= new BlobInfoFactory();
	    BlobInfo info = infof.loadBlobInfo(blobKey);
	    String zipFileName = util.getFileName(info.getFilename());

	    //XEResource parent = rm.newFolder(root,zipFileName);
	    XEResource parent = root;
	    
	    String curPath = "";  
	    while((entry = zis.getNextEntry()) != null) {
	    		System.out.println("Extracting: " +entry);
	    		//dir
	    		String fullPath = entry.getName();
	    		String entryDir = util.getDirName(fullPath);
	    		
	    		if (fullPath.contains("css")){
	    			int y=1;
	    			y++;
	    		}
	    		//comp

	    		
	    		if (entry.isDirectory()) {
	    			XEResource r = rm.newFolder(parent, entryDir);
	    			parent = r;
	    		}	
		    	else { //dir found -> upload new blob. 
		    			 String parentDir  = util.getParentDirName(fullPath,false);
		    			 
		    			 XEResource dir = rm.findByKey(parentDir) ;
		    			 if (dir!=null) 
		    				 parent=dir;
		    			 
		 	    		String fileName = util.getFileName(fullPath); 
			    		String fileExt = util.getFileExt(fullPath);
			    		String fileNameExt= fileName + "." + fileExt;

		    			 String compSimpleName = fileName; 
		    			 
		    			 BufferedOutputStream dest = null; 
			        	  
			 	         FileService fileService = FileServiceFactory.getFileService();
			
			 	         String mime = util.getMimeTypeByFileName(fileNameExt);
			 	         AppEngineFile file = fileService.createNewBlobFile(mime,fileNameExt);
			 	         
			
			 	         // Open a channel to write to it
			 	         boolean lock = true;
			
			 	         FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
			
			 	         
				         int count;
				         byte data[] = new byte[BUFFER];
		
				         ByteArrayOutputStream fos = new ByteArrayOutputStream();
				         dest = new  BufferedOutputStream(fos, BUFFER);
		
				         String source="";
			            
				         while ((count = zis.read(data, 0, BUFFER)) != -1) {
				        	 dest.write(data, 0, count);
				               
			         	     writeChannel. write(ByteBuffer.wrap(data,0,count));
			         	     if (util.isSource(entry.getName())){
			             	         String line=new String (data);
			             	         source+=line;
			         	     }
				         }
			             dest.flush();
			             dest.close();
			            
			   	         // Now finalize
			   	         writeChannel.closeFinally();
		
			   	         BlobKey fbkey = fileService.getBlobKey(file);
			   	         XEResource r = rm.newResource(fbkey ,parent );
		    	    } 
	 	         }
		         zis.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
}
